package View;

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;

import javax.swing.JOptionPane;
import javax.swing.JPanel;



public class Server extends Thread{
	private ClientManager manager;
	private String file = "ClientList.xml";
	private ServerSocket server;
	public Server(){
		manager = new ClientManager();
		try {
			server = new ServerSocket(3007);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		start();
	}
	
	public void run(){
		try {
			do
			{
				Socket client = server.accept();
				//System.out.println("Server has connected!!");
				InputStream is = client.getInputStream();
				ObjectInputStream ois = new ObjectInputStream(is);
				
				OutputStream os = client.getOutputStream();
				ObjectOutputStream oos = new ObjectOutputStream(os);
				String receive = null;
				String[] received = new String[2];
				received[0] = "";
				received[1] = "";
				
				for(int i = 0; i < received.length; i++)
				{
					receive = ois.readUTF();
					System.out.println("receive: " + receive);
					received[i] = receive;
				}
				
				if(manager.testInformation(file, received[0], received[1]) == 0){
					oos.writeUTF("0");
					oos.flush();
				}else{
					oos.writeUTF("1");
					oos.flush();
				}
				CommanderServer cmdServer = new CommanderServer(client);
				
			}while(true);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			JOptionPane.showMessageDialog(ServerScreen.frame, "Connection failed!");
			//e.printStackTrace();
		}
								
		JOptionPane.showMessageDialog(null, "Server Thread closed", 
			    "Error", JOptionPane.ERROR_MESSAGE);
	}
}
